package com.android.place360.geocoding;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.android.place360.services.HttpService;


public class GooglePlaceAutoComplete {
	
	public static String GPA_URL = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key=@APIKEY&language=@LANGUAGE&sensor=true&input=@INPUT";
	
	public static List<String> getGPAPlaces(String input, String api_key, String language){
		String request =  GPA_URL;
		request = request.replace("@APIKEY", api_key);
		request = request.replace("@LANGUAGE", language);
		request = request.replace("@INPUT", input);
		request = request.replace(" ", "%20");
		
		
		String jResponse = HttpService.SendRequest(request);
		if(jResponse == null) return null;
		return ParseResponse(jResponse);
	}
	
	public static List<String> ParseResponse(String jsonString){
		try {
			ArrayList<String> lst = new ArrayList<String>();
			JSONObject obj = new JSONObject(jsonString);
			String code = obj.getString("status");
			
			if(code.equalsIgnoreCase("OK")){
				JSONArray predictions = obj.getJSONArray("predictions");
				
				for (int i = 0; i < predictions.length(); i++) {
					obj = predictions.getJSONObject(i);
					String desc;
					desc=obj.getString("description");
					lst.add((desc.toString()));
					
				}
				return lst;
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
}
